package com.medvalley.tcm.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Created by LinSong on 2018/3/7.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 系统错误
     *
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handleException(Exception exception, HttpServletRequest request) {
        printMethodParameters(request);
        LOGGER.error("catch Exception，the detail message:", exception); //打印异常堆栈详情
        return new Result(Constants.HTTP_ERROR_CODE, "服务器错误");
    }

    @ExceptionHandler(value = {EmptyException.class, NoSuchElementException.class})
    @ResponseBody
    public Result handleException(EmptyException exception, HttpServletRequest request) {
        printMethodParameters(request);
        return new Result(Constants.HTTP_ERROR_CODE, exception.getMessage());
    }

    @ExceptionHandler(value = {BusinessException.class})
    @ResponseBody
    public Result handleException(BusinessException exception, HttpServletRequest request) {
        printMethodParameters(request);
        LOGGER.warn(exception.getMessage(), exception);
        return new Result(Constants.HTTP_ERROR_CODE, exception.getMessage());
    }

    /**
     * 记录方法的入参
     *
     * @param request
     */
    public void printMethodParameters(HttpServletRequest request) {
        StringBuffer log = new StringBuffer();
        log.append("url=").append(request.getServletPath());
        if (request.getQueryString() != null) {
            log.append(request.getQueryString()).append(" - ");
        } else {
            Map<String, String[]> parameters = request.getParameterMap();
            if (parameters.size() != 0) {
                log.append(" - [");
            }
            for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                String message = "";
                if (value.getClass().isArray()) {
                    Object[] args = (Object[]) value;
                    message = " " + key + "=" + Arrays.toString(args) + " ";
                } else {
                    message = key + "=" + String.valueOf(value) + " ";
                }
                log.append(message);
            }
            if (parameters.size() != 0) {
                log.append("]");
            }
        }
        LOGGER.info(log.toString());
    }
}
